function createDialogue(peer, conn = null) {
    const tpl = `
                <div class="dialogue">
                    <a class="close-btn">关闭</a>
                    <div class="remote-peer-info">
                        <input type="text" placeholder="请输入远端peer_id">
                    </div>

                    <div class="recives">
                        <span class="text"></span>
                        <span class="reviced-time"></span>
                    </div>

                    <div class="sends">
                        <textarea name="message" cols="30" rows="2" placeholder="请输入发送的消息"></textarea>
                        <button>发送</button>
                    </div>

                    <div class="error">
                        <p class="text"></p>
                        <p class="occur-time"></p>
                    </div>
                </div>
            `;

    const $dialoguesContainer = $('#dialogues-container');
    const $dialogue = $(tpl);
    const $remotePeerInfo = $dialogue.find('.remote-peer-info');
    const $recives = $dialogue.find('.recives');
    const $sends = $dialogue.find('.sends');
    const $error = $dialogue.find('.error');

    function listenConn(conn) {
        conn.on('open', function () {
            $remotePeerInfo.find('input').attr('disabled', true);
            $remotePeerInfo.find('button').text('断开').removeAttr('disabled');
            $sends.find('textarea,button').removeAttr('disabled');
        });
        conn.on('close', function () {
            $remotePeerInfo.find('input').removeAttr('disabled');
            $remotePeerInfo.find('button').text('连接').removeAttr('disabled');
            $sends.find('textarea,button').attr('disabled', true);
        });
        conn.on('data', function (data) {
            const now = new Date();
            $recives.find('.text').text(data);
            $recives.find('.reviced-time').text(now.toLocaleString());
        });
        conn.on('error', function (err) {
            const now = new Date();
            $error.find('.text').text(err);
            $error.find('.occur-time').text(now.toLocaleString());
        });
    }

    if (!conn) {
        $remotePeerInfo.append('<button>连接</button>');
        $sends.find('textarea,button').attr('disabled', true);
    } else {
        const peer_id = conn.metadata.peer_id;
        $remotePeerInfo.find('input').val(peer_id).attr('disabled', true);
        $remotePeerInfo.append('<button>断开</button>');
        $sends.find('textarea,button').removeAttr('disabled');
        listenConn(conn);
    }

    // 连接/断开
    $remotePeerInfo.find('button').on('click', function () {
        $btn = $(this);
        if (!conn) {
            const remote_peer_id = $remotePeerInfo.find('input').val().trim();
            if (!remote_peer_id) {
                alert('Peer id 不能为空!');
                return;
            }
            $btn.attr('disabled', true);
            conn = peer.connect(id = remote_peer_id, options = {
                label: 'hi',
                metadata: {
                    peer_id: peer.id
                },
                serialization: 'json',
            });
            listenConn(conn);
        } else {
            conn.close();
            conn = null;
            $btn.attr('disabled', true);
            $remotePeerInfo.find('button').text('连接');
            $remotePeerInfo.find('button').removeAttr('disabled');
            $sends.find('textarea,button').attr('disabled', true);
        }
    });

    // 发送消息
    $sends.find('button').on('click', function () {
        if (!conn) {
            alert('未连接!');
            return;
        }
        const message = $sends.find('textarea').val();
        conn.send(message);
    });

    // 关闭对话
    $dialogue.find('>.close-btn').on('click', function () {
        if (conn) {
            conn.close();
        }
        $dialogue.remove();
    })

    $dialoguesContainer.append($dialogue);
}

$(document).ready(function () {
    console.log('Document is ready.');

    const peer = new Peer();
    peer.on('open', function(id) {
        console.log(id);
        $('#peer_id').text(id);
        window.isInitFinish = true;
    });
    peer.on('connection', function (conn) {
        createDialogue(peer, conn);
    });
    peer.on('error', function (err) {
        $('#error').text(err);
    });

    $('#create-btn').on('click', function (event) {
        createDialogue(peer);
    });
});
